package com.animerank.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 统一的CORS配置类
 * 使用FilterRegistrationBean确保CORS过滤器在所有过滤器中优先级最高
 */
@Configuration
public class MyCorsConfiguration {

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        // 创建CORS配置对象
        CorsConfiguration config = new CorsConfiguration();
        
        // 设置允许的来源
        config.addAllowedOriginPattern("*");
        
        // 设置允许发送Cookie
        config.setAllowCredentials(false);
        
        // 设置允许的请求方法
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("OPTIONS");
        
        // 设置允许的请求头
        config.addAllowedHeader("*");
        
        // 设置暴露的响应头
        config.addExposedHeader("Authorization");
//        config.addExposedHeader("satoken");
        
        // 设置预检请求的有效期（秒）
        config.setMaxAge(3600L);
        
        // 创建CORS源对象并注册配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        
        // 创建过滤器注册Bean
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        
        // 设置过滤器顺序为最高优先级
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        
        return bean;
    }
}